package hu.ngms.jpf.maven;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Looks for Java classes in the specified Java package hierarchy that match the given pattern.
 */
public class JavaClassFinder {
	
	private List<String> folders;
	
	private String pattern;
	
	public JavaClassFinder(List<String> folders, String pattern) {
		this.folders = folders;
		this.pattern = pattern;
	}

	public JavaClassFinder(List<String> folders) {
		this(folders, "");
	}

	public List<String> findClasses() throws IOException {
		List<String> allTestClasses = new ArrayList<String>();
		for (String dir : folders) {
			List<String> testClasses = findJavaClassesIn(new File(dir));
			allTestClasses.addAll(testClasses);
		}
		return allTestClasses;
	}
	
	private List<String> findJavaClassesIn(File testFolder) throws IOException {
		List<String> javaClasses = new ArrayList<String>();
		
		for (File file : testFolder.listFiles()) {
			if (file.isDirectory()) {
				List<String> classes = findJavaClassesIn(file);
				javaClasses.addAll(classes);
			} else if (file.getName().endsWith(".java") && file.getName().contains(pattern)) {
				BufferedReader reader = null;
				String packagePrefix = "";
				try {
					reader = new BufferedReader(new FileReader(file));
					String line = null;
					while ((line = reader.readLine()) != null) {
						if (line.trim().startsWith("package ")) {
							packagePrefix = line.replace("package", "").replace(";", "").trim() + ".";
						}
						break;
					}
					String className = packagePrefix + file.getName().replace(".java", "");
					javaClasses.add(className);
				} finally {
					if (reader != null) {
						reader.close();
					}
				}
			}
		}
		
		return javaClasses;
	}


}
